var http = require('http');
var cheerio = require('cheerio');
var fs = require('fs');
var BufferHelper = require('bufferhelper');

//重写request方法,加入option.timeout
http.request = (function (_request) {
    return function (options, callback) {
        var timeout = options['timeout'],
            timeoutEventId;
        var req = _request(options, function (res) {
            res.on('end', function () {
                clearTimeout(timeoutEventId);
                console.log('response end...');
            });

            res.on('close', function () {
                clearTimeout(timeoutEventId);
                console.log('response close...');
            });

            res.on('abort', function () {
                console.log('abort...');
            });

            callback(res);
        });

        //超时
        req.on('timeout', function () {

            req.abort();
        });

        //如果存在超时
        timeout && (timeoutEventId = setTimeout(function () {
            req.emit('timeout', {message: 'have been timeout...'});
        }, timeout));
        return req;
    };

})(http.request)

exports.getdate = {
    options: {
        hostname: '',
        port: 80,
        path: '',
        method: 'GET',
        timeout: 15000
    },
    bjpk10day: function (todaystr, page, callback) {
        console.log('进入code内pk10函数');
        this.options.hostname = 'www.bwlc.net';
        this.options.path = '/bulletin/prevtrax.html?dates=' + todaystr + '&page=' + page;
        var req = http.request(this.options, function (res) {
            var bufferHelper = new BufferHelper();
            /*console.log('STATUS: ' + res.statusCode);
             console.log('HEADERS: ' + JSON.stringify(res.headers));*/
            res.on('data', function (chunk) {
                bufferHelper.concat(chunk);
                console.log('res.on.data...loading')
            });
            res.on('end', function () {
                console.log('res.on.end');
                var html = bufferHelper.toBuffer().toString();
                if (html.indexOf('</html>') > -1) {
                    console.log('进入jq读取数据阶段');
                    var $ = cheerio.load(html);
                    fs.writeFile('historypk10html' + page + '.txt', '\r\n historypk10 -- ' + todaystr + '数据' + new Date() + $(".tb tr").text(), {
                        flag: 'a'
                    }, function (err) {
                        if (err) console.log(err);
                    });
                    var props = ["gamenum", "ballnum", "gametime"];
                    var objs = new Array();
                    $(".tb tr").each(function () {
                        var obj = new Object();
                        $(this).find("td").each(function (n) {
                            obj[props[n]] = $(this).html();
                        });
                        objs.push(obj);
                    });
                    //删除第一个空元素,第一个是th所以循环了一个空元素
                    objs.shift();
                    if (objs.length) {
                        callback(objs);
                    } else {
                        console.log('code拿到的数据为空(如在每日09:07分前属于正常情况)')
                        callback('empty')
                    }
                } else {
                    console.log('拿到的html没有结尾');
                    callback([])
                }
            });
        });
        req.on('error', function (e) {
            console.log("error got :" + e.message);
            callback('error')
        }).on('timeout', function (e) {
            console.log('timeout got :' + e.message);
        });
        req.end();
    },
    bjklday: function (todaystr, page, callback) {
        console.log('进入code内pk10函数');
        this.options.hostname = 'www.bwlc.net';
        this.options.path = '/bulletin/prevkeno.html?dates=' + todaystr + '&page=' + page;

        var req = http.request(this.options, function (res) {
            var bufferHelper = new BufferHelper();
            /*console.log('STATUS: ' + res.statusCode);
             console.log('HEADERS: ' + JSON.stringify(res.headers));*/
            res.on('data', function (chunk) {
                bufferHelper.concat(chunk);
                console.log('res.on.data...loading')
            });
            res.on('end', function () {
                console.log('res.on.end');
                var html = bufferHelper.toBuffer().toString();
                if (html.indexOf('</html>') > -1) {
                    console.log('进入jq读取数据阶段');
                    var $ = cheerio.load(html);
                    fs.writeFile('historybjklhtml' + page + '.txt', '\r\n historybjkl -- ' + todaystr + '数据' + new Date() + $(".tb tr").text(), {
                        flag: 'a'
                    }, function (err) {
                        if (err) console.log(err);
                    });
                    var props = ["gamenum", "ballnum", "ballsnum", "gametime"];
                    var objs = new Array();
                    $(".tb tr").each(function () {
                        var obj = new Object();
                        $(this).find("td").each(function (n) {
                            obj[props[n]] = $(this).html();
                        });
                        objs.push(obj);
                    });
                    //删除第一个空元素,第一个是th所以循环了一个空元素
                    objs.shift();
                    if (objs.length) {
                        callback(objs);
                    } else {
                        console.log('code拿到的数据为空(如在每日09:07分前属于正常情况)')
                        callback('empty')
                    }
                } else {
                    console.log('拿到的html没有结尾');
                    callback([])
                }
            });
        });
        req.on('error', function (e) {
            console.log("error got :" + e.message);
            callback('error')
        }).on('timeout', function (e) {
            console.log('timeout got :' + e.message);
        });
        req.end();
    },
    jndkeno: function (todaystr, callback) {
        console.log('进入code内jndkeno函数');
        this.options.hostname = 'www.wclc.com';
        this.options.path = '/winning-numbers/keno.htm?selDate=' + todaystr;

        var req = http.request(this.options, function (res) {
            var bufferHelper = new BufferHelper();
            /*console.log('STATUS: ' + res.statusCode);
             console.log('HEADERS: ' + JSON.stringify(res.headers));*/
            res.on('data', function (chunk) {
                bufferHelper.concat(chunk);
                console.log('res.on.data...loading')
            });
            res.on('end', function () {
                console.log('res.on.end');
                var html = bufferHelper.toBuffer().toString();
                if (html.indexOf('</html>') > -1) {
                    console.log('进入jq读取数据阶段');
                    var $ = cheerio.load(html);
                    fs.writeFile('historyjndkenohtml.txt', '\r\n historyjndkeno -- ' + todaystr + '数据' + new Date() + $(".tb tr").text(), {
                        flag: 'a'
                    }, function (err) {
                        if (err) console.log(err);
                    });
                    var props = ["gamenum", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20"];
                    var objs = new Array();
                    $(".kenoTable tr").each(function () {
                        var obj = new Object();
                        $(this).find("td").each(function (n) {
                            obj[props[n]] = $(this).html();
                        });
                        objs.push(obj);
                    });
                    //删除第一个空元素,第一个是th所以循环了一个空元素
                    objs.shift();
                    if (objs.length) {
                        callback(objs);
                    } else {
                        console.log('code拿到的数据为空(如在每日09:07分前属于正常情况)')
                        callback('empty')
                    }
                } else {
                    console.log('拿到的html没有结尾');
                    callback([])
                }
            });
        });
        req.on('error', function (e) {
            console.log("error got :" + e.message);
            callback('error')
        }).on('timeout', function (e) {
            console.log('timeout got :' + e.message);
        });
        req.end();
    }
};
